import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { Role, RoleType } from '../../entities/role.entity';
import { Permission } from '../../entities/permission.entity';
import { User } from '../../entities/user.entity';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private roleRepository: Repository<Role>,
    @InjectRepository(Permission)
    private permissionRepository: Repository<Permission>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async createRole(name: string, code: string, description?: string, type: RoleType = RoleType.CUSTOM) {
    const existingRoleName = await this.roleRepository.findOne({ where: { name } });
    if (existingRoleName) {
      throw new BadRequestException('角色名已存在');
    }

    const existingRoleCode = await this.roleRepository.findOne({ where: { code } });
    if (existingRoleCode) {
      throw new BadRequestException('角色代码已存在');
    }

    const role = this.roleRepository.create({ name, code, description, type });
    return this.roleRepository.save(role);
  }

  async updateRole(id: string, name?: string, code?: string, description?: string, type?: RoleType) {
    const role = await this.roleRepository.findOne({ where: { id } });
    if (!role) {
      throw new NotFoundException('角色不存在');
    }

    if (name && name !== role.name) {
      const existingRole = await this.roleRepository.findOne({ where: { name } });
      if (existingRole) {
        throw new BadRequestException('角色名已存在');
      }
      role.name = name;
    }

    if (code && code !== role.code) {
      const existingRole = await this.roleRepository.findOne({ where: { code } });
      if (existingRole) {
        throw new BadRequestException('角色代码已存在');
      }
      role.code = code;
    }

    if (description !== undefined) {
      role.description = description;
    }

    if (type !== undefined) {
      role.type = type;
    }

    return this.roleRepository.save(role);
  }

  async deleteRole(id: string) {
    const role = await this.roleRepository.findOne({ 
      where: { id },
      relations: ['users']
    });
    
    if (!role) {
      throw new NotFoundException('角色不存在');
    }

    if (role.users?.length > 0) {
      throw new BadRequestException('该角色下还有用户，无法删除');
    }

    await this.roleRepository.remove(role);
    return { message: '角色删除成功' };
  }

  async assignPermissionsToRole(roleId: string, permissionIds: string[]) {
    const role = await this.roleRepository.findOne({ 
      where: { id: roleId },
      relations: ['permissions']
    });

    if (!role) {
      throw new NotFoundException('角色不存在');
    }

    const permissions = await this.permissionRepository.find({
      where: { id: In(permissionIds) }
    });
    
    if (permissions.length !== permissionIds.length) {
      throw new BadRequestException('部分权限不存在');
    }

    role.permissions = permissions;
    return this.roleRepository.save(role);
  }

  async assignRolesToUser(userId: string, roleIds: string[]) {
    const user = await this.userRepository.findOne({ 
      where: { id: userId },
      relations: ['roles']
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    const roles = await this.roleRepository.find({
      where: { id: In(roleIds) }
    });
    
    if (roles.length !== roleIds.length) {
      throw new BadRequestException('部分角色不存在');
    }

    user.roles = roles;
    return this.userRepository.save(user);
  }

  async getRoles() {
    return this.roleRepository.find({
      relations: ['permissions'],
      order: { createdAt: 'DESC' }
    });
  }

  async getRoleById(id: string) {
    const role = await this.roleRepository.findOne({ 
      where: { id },
      relations: ['permissions', 'users']
    });

    if (!role) {
      throw new NotFoundException('角色不存在');
    }

    return role;
  }
} 